package com.xx.dk.tbsalling.aismessages.utils;

import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;

public class LimitedSizeQueue<E> extends ArrayBlockingQueue<E>{
    public LimitedSizeQueue(int capacity) {
        super(capacity);
    }

    public synchronized boolean add(E e) {
        // 如果队列已满，则先移除队列头部的元素
        if (super.remainingCapacity() == 0) {
            super.poll();
        }
        // 添加新元素到队列尾部
      return super.add(e);
    }

    public synchronized E remove()  {
        try {
            return super.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public String toString() {
        Iterator<E> it = super.iterator();
        if (!it.hasNext())
            return "[]";
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (; ; ) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (!it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }
}
